package com.tyylab.message.core.service;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Preconditions;
import com.tyylab.message.core.config.properties.TyylabMessageRedisProperties;
import com.tyylab.message.core.model.TransMessage;
import io.lettuce.core.api.StatefulRedisConnection;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import java.time.LocalDateTime;

/**
 * 信息发布
 */
public class SyncPublishSevice implements ISyncPublish {
    @Autowired
    @Qualifier("writeConn")
    StatefulRedisConnection<String,String> redisConnection;

    @Autowired
    TyylabMessageRedisProperties simulMessageRedisProperties;

    String app="";
    String ip="";
    String port="";

    @Autowired
    ApplicationContext context;

    @Autowired
    public void init(){
        try {
            Environment environment = context.getBean(Environment.class);
            port= environment.getProperty("server.port");
            app= environment.getProperty("spring.application.name");
            InetAddress address =  InetAddress.getLocalHost();
            ip = address.getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void publish(TransMessage message) {
        String channel = simulMessageRedisProperties.getBus();
        publishMsg(channel,message);
    }

    @Override
    public void publish(TransMessage message, String channel) {
        publishMsg(channel,message);
    }


    private void publishMsg(String channel, TransMessage transMessage){
        Preconditions.checkNotNull(transMessage,"simul message cannot be null.");
        Preconditions.checkArgument(StringUtils.isNotBlank(channel),"channel cannot be blank.");
        transMessage.setIp(ip);
        transMessage.setApp(app);
        transMessage.setPort(port);
        if (null == transMessage.getCreateTime()){
            transMessage.setCreateTime(Timestamp.valueOf(LocalDateTime.now()));
        }
        String json = JSONObject.toJSONString(transMessage);
        redisConnection.sync().lpush(channel,json);
    }
}
